package cn.yuysaln.domain.strategy.service.rule.filter.factory;

import cn.yuysaln.domain.strategy.model.entity.RuleActionEntity;
import cn.yuysaln.domain.strategy.service.annotation.LogicStrategy;
import cn.yuysaln.domain.strategy.service.rule.filter.ILogicFilter;
import lombok.AllArgsConstructor;
import lombok.Getter;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
@Service
public class DefaultLogicFactory {
    public Map<String, ILogicFilter<?>> logicFilterMap = new ConcurrentHashMap<>();

    /**
     * 扫描logicFilters，查看是否配置了过滤逻辑，有的话填充到Map中
     * @param logicFilters
     */
    public DefaultLogicFactory(List<ILogicFilter<?>> logicFilters) {
        logicFilters.forEach(logic -> {
            LogicStrategy strategy = AnnotationUtils.findAnnotation(logic.getClass(), LogicStrategy.class);
            if (null != strategy) {
                logicFilterMap.put(strategy.logicMode().getCode(), logic);
            }
        });
    }


    /**
     * 向外提供访问接口
     * @return
     * @param <T>
     */
    public <T extends RuleActionEntity.RaffleEntity> Map<String, ILogicFilter<T>> openLogicFilter() {
        return (Map<String, ILogicFilter<T>>) (Map<?, ?>) logicFilterMap;
    }

    @Getter
    @AllArgsConstructor
    public enum LogicModel {

        RULE_WIGHT("rule_weight","【抽奖前规则】根据抽奖权重返回可抽奖范围KEY","before"),
        RULE_BLACKLIST("rule_blacklist","【抽奖前规则】黑名单规则过滤，命中黑名单则直接返回","before"),
        RULE_LOCK("rule_lock","【抽奖中规则】，抽奖N次可以解锁奖品","center"),
        RULE_LUCK_AWARD("rule_luck_award","【抽奖后规则】，幸运奖兜底","after")
        ;

        private final String code;
        private final String info;
        private final String type;


        /**
         * 根据 code 查找对应的 LogicModel 枚举实例
         * @param code 逻辑模型的代码
         * @return 对应的 LogicModel 实例，如果未找到则返回 null
         */
        public static LogicModel fromCode(String code) {
            if (code == null) {
                return null;
            }
            for (LogicModel model : LogicModel.values()) {
                if (model.getCode().equalsIgnoreCase(code)) {
                    return model;
                }
            }
            return null;
        }

        //先通过 fromCode 方法获取对应的枚举实例。
        //检查实例是否为 null，然后比较其 type 字段。
        public static boolean isCenter(String code) {
            LogicModel model = fromCode(code);
            return model != null && "center".equals(model.getType());
        }

        public static boolean isAfter(String code) {
            LogicModel model = fromCode(code);
            return model != null && "after".equals(model.getType());
        }

    }


}
